import math

from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt

from App.models import User


def home(request):
    # return HttpResponse("hello,this is home")
    return render(request, "home/home.html", context={
        "title": "我是标题",
        "txt": "我是注释内容",
        "number": 20,
        "list": ["tom", "李白", "杜甫"],
        "lists": [
            {
                "name1": "后裔1",
                "age": 18,
                "sex": "男",
            },
            {
                "name1": "后裔2",
                "age": 19,
                "sex": "男",
            },
        ],
        "doc_list": {
            "name": "步惊云",
            "age": 54
        }
    })


def page(request, number):
    # 请求对象 request
    # 常用属性 GET POST  返回字典
    # methods 请求方法

    # GET
    print(request.GET.get("username"))  # http://127.0.0.1:8000/page/100/?username="tom"

    # POST
    print(request.POST.get("username"))  # 测试时需关闭settings中的csrf拦截

    print(request.method)  # POST
    print(request.path)  # /page/100/

    return HttpResponse("分页{}".format(number))


def resjson(request):
    # return JsonResponse({"name":"tome1"})   # 返回json 数据
    return JsonResponse([1, 2, 3], safe=False)  # 返回的不是字典型数据


def login(request):
    # 登录成功后重定向
    return redirect("home")


# @csrf_exempt         # 本实例不 csrf
def ajax(request):
    if request.is_ajax():
        print("111")
        return JsonResponse({
            "code": 200,
            "msg": "ok",
            "list": [1, 2, 3, 4]
        })
    return HttpResponse("hello")


def sql(request):
    # 添加一条数据
    # username=request.GET.get('username')
    # password = request.GET.get('password')
    # pagenumber=int(request.GET.get('pagenumber',3))   #每页条数,int***
    # pagesize = int(request.GET.get('pagesize',1) )     #第几页

    # 新增一条数据
    # stu=User(username="直接", age=19,sex="男")
    # stu.save()

    # return HttpResponse("ok")

    # 查询出全部数据
    # stu = User.objects.all()
    # stu = User.objects.all()[0:3]   # 输出前3个

    # 查询出满足条件的
    # stu=User.objects.filter(username='李白')

    # count 满足条件的条数
    # stu = User.objects.filter(sex="男").count()

    # 升序查询
    # stu=user.objects.order_by('id')

    # 降序查询
    # stu = user.objects.order_by('-id')

    # id大于15的，也可以用在日期上
    # stu=User.objects.filter(id__gt='6')   #id__gte   表示>=   id__lt  <

    # id=15或16
    # stu=user.objects.filter(id__in=('15','16'))

    # 10<id<16
    # stu = user.objects.filter(id__range=('10', '16'))

    # 模糊查询
    # stu = User.objects.filter(sex__contains='n')  # 包含
    # stu = user.objects.filter(username__startswith='t',password__contains='123')  # 开头包含
    # stu = user.objects.filter(username__endswith='3')  # 结尾包含

    # 删除一条数据
    # user.objects.filter(id=14).delete()

    # 修改一条记录
    # user.objects.filter(id=13).update(username='aaa')

    # print(stu)
    return HttpResponse("ok")


# 分页查询
def pages(request):
    pagenumber = int(request.GET.get('pagenumber', 3))  # 每页条数,int***
    pagesize = int(request.GET.get('pagesize', 1))  # 第几页

    # 查询所有数据
    users = User.objects.all()

    nums = User.objects.count()  # 总条数
    print(nums)

    # 创建分页器对象
    pager = Paginator(users, pagenumber)

    # 获取当前页数据
    try:
        userdata = pager.page(pagesize)
    except PageNotAnInteger:
        userdata = pager.page(1)
    except EmptyPage:
        userdata = pager.page(pager.num_pages)  # 返回最后一页数据

    # data1 = {}
    # data1['list'] = list(userdata)
    # return JsonResponse(data1,safe=False)
    return HttpResponse(userdata)
